const Koa = require('koa')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const websockify = require('koa-websocket');
const cors = require('koa-cors');

const router = require('./router')
const websocketRouter = require('./router/websocket.js')

const app = websockify(new Koa());


app.use(cors({
  origin: '*'
}))

app.ws.use((ctx, next) => {
  return next(ctx);
})

onerror(app)

app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

app.use(router.routes(), router.allowedMethods())
app.ws.use(websocketRouter.routes(), websocketRouter.allowedMethods());
app.listen(8000);

module.exports = app
